import { RedisModuleOptions } from '@liaoliaots/nestjs-redis';
import { TypedConfigService } from 'src/config/typed-config.service';

export const getRedisConfig = (
  configService: TypedConfigService,
): RedisModuleOptions => {
  const redisConfig = configService.get('redis');

  return {
    config: {
      host: redisConfig.host,
      port: redisConfig.port,
      password: redisConfig.password,
      db: 0,
      // 连接和命令超时配置
      connectTimeout: 60000, // 连接超时 60 秒
      commandTimeout: 5000,  // 命令超时 5 秒
      // 重试配置
      maxRetriesPerRequest: 3,
      // 心跳保活配置
      keepAlive: 30000, // 30 秒心跳
      family: 4, // 使用 IPv4
      // 连接池配置
      lazyConnect: true,
      // 错误处理
      enableOfflineQueue: false,
      // 重连策略 - 当遇到特定错误时进行重连
      reconnectOnError: (err) => {
        // 对于 Socket 关闭错误，返回 true 进行重连
        const shouldReconnect = err.message.includes('ECONNRESET') ||
                               err.message.includes('ENOTFOUND') ||
                               err.message.includes('ETIMEDOUT') ||
                               err.message.includes('Socket closed unexpectedly');

        if (shouldReconnect) {
          console.log(`Redis 重连触发: ${err.message}`);
        }

        return shouldReconnect;
      },
    },
  };
};
